<?php

/*
 * 标题：阿里紫订单管理系统
 * 作者：忆天网络 QQ715457186 
 * 官方网址：www.fjd100.com||www.yi66.net
 */
defined('THINK_PATH') OR exit();
class OrderAction extends AliziAction {

    public function _initialize(){
        parent::_init();
    }

    public function index($id,$tpl='index'){
		// var_dump($id);
		// var_dump($tpl);die;
	    if(empty($id) || !ctype_alnum($id))$this->error(lang('error'));
		
		global $info;
        $info  = M('Item')->where(array('sn'=>$id))->find();//$info  = getCache('Item',array('sn'=>$id));
		
		
		if(empty($info) || $info['is_delete']==1) $this->error(lang('empty_item'));
		
		if(!empty($info['redirect_url'])){
			header("location:".$info['redirect_url']);exit;
		}else{
			$domains= array_filter(explode("<br />",nl2br($this->aliziConfig['redirect_domains'])));

			if($_SERVER['HTTP_HOST']==$this->aliziConfig['main_domain'] && $tpl=='detail' && $domains){
				$redirect = trim($domains[array_rand($domains)].$_SERVER['REQUEST_URI']);
				header("location:".$redirect);exit;
			}
		}
		
        
        $template  = getCache('ItemTemplate',array('id'=>$info['id']),true);
        $template['extend'] = unserialize($template['extend']);
        $template['color'] = json_decode($template['color'],true);
        if(isset($_GET['theme'])) $template['template']=str_replace('-', '/', $_GET['theme']);

        $info['content'].='<p style="border: 0px;">{[AliziOrder]}</p><p style="border: 0px;">{[AliziComment-1]}</p>';
		if($tpl=='detail'){
			$_GET['page'] = 'detail';
			$tpl = file_exists(TMPL_PATH.'Alizi/'.$template['template'].'/detail.html')?"Alizi/{$template['template']}/detail":'Order/detail';
        }else{
			$_GET['page'] = 'single';
			$info['content'] = "{[AliziOrder]}";
            $tpl = "Order/".$tpl;
        }

		$_GET['id'] = $id;

		preg_match("/(\{\[AliziComment\-(\d+)\]\})/",$info['content'],$matches);
		if($matches){
			$_GET['commentTpl'] = $matches[2];
			$info['content'] = preg_replace("/(\{\[AliziComment\-(\d+)\]\})/",R('Widgets/comment',array('request'=>$_GET)),$info['content']);  //评论
		}
		preg_match_all("/(\{\[AliziScroll\-(\d+)\]\})/",$info['content'],$matches);

		if($matches){
			foreach($matches[2] as $sid){
				$info['content'] = str_replace('{[AliziScroll-'.$sid.']}',R('Widgets/scroll',array('request'=>$_GET,'id'=>$sid)),$info['content']);
			}
		}
		$info['content'] = preg_replace("/(\{\[AliziScroll\-(\d+)\]\})/","",$info['content']);
		$info['content'] = preg_replace("/(\{\[AliziOrder\]\})/",R('Widgets/form',array('request'=>$_GET)),$info['content']);//添加商品
		// $infocontent = R('Widgets/form',array('request'=>$_GET));
		// var_dump($infocontent);  template    {[AliziOrder]} {[AliziComment-5]}

		//加密内容
		if($this->aliziConfig['is_encode']){
			$info['content'] = '<script tyle="text/javascript" src="'.$this->aliziHost.'Public/Alizi/seajs/alizi/base64.js?v='.ALIZI_VERSION.'"></script><script tyle="text/javascript">var content="Alizi'.base64_encode($info['content']).'";var b = new Base64();document.write(b.decode(content));</script>';
		}


		$this->assign('template',$template);
		
		// var_dump($info);
		$facebookpixels=explode(',',$info['facebook_pixels']);
		// $wwwwwwww = '';
		foreach($facebookpixels as $facebooks){
            $fbxs_id .= "fbq('init', '$facebooks', {em: 'insert_email_variable,'});\n"; 
			
       }
	   // $wwwwwwww = preg_replace(";;",';',$wwwwwwww);//添加商品
        $this->assign('info',$info);
        $this->assign('facebookpixels',$facebookpixels);
        $this->assign('fbxs_id',$fbxs_id);
       // ob_start(); //开启缓存区
		
		//createHtml($url,$dir,$filename);//die;
		
        if(isset($_GET['buildHtml'])){
			$id = intval($_GET['uid'])<=1?$id:$id.'-'.$_GET['uid'];
			$html = $this->aliziHost.$this->aliziConfig['html_file'].$id.C('HTML_FILE_SUFFIX');
			$this->assign('thisUrl',$html);
			
            $this->buildHtml($id,$this->aliziConfig['html_file']?$this->aliziConfig['html_file']:'./',$tpl);
            header("location:".$html);
        }else{
			$html = $this->host.urlencode($_SERVER['REQUEST_URI']);
			$this->assign('thisUrl',$html);
			// $this->buildHtml($id,$this->aliziConfig['html_file']?$this->aliziConfig['html_file']:'./',$tpl);
			
			$this->display($tpl);
			//file_put_contents('index.html', ob_get_contents());
			
		}
    }

    public function aliziBooking(){
		if(isset($_POST['name']))$_POST['name'] = strFilter($_POST['name']);
        $_POST['sign'] = createSign($_POST,C('ALIZI_KEY'));
		
        $result = R('Api/aliziBooking',array('data'=>$_POST));

        $data  = array();
        if($result['status']==1){
            $data = array('order_id'=>$result['data']['order_id'],'order_no'=>$result['data']['order_no']);
        }else{
            file_put_contents('./Err.txt',var_export($result,true)."\n",FILE_APPEND);
        }
		
        if(IS_AJAX){
            $this->ajaxReturn($data,$result['message'],$result['status']);
        }else{
            if($result['status']==1){
                header("location:".U('Order/pay',array('order_no'=>$data['order_no'])));
            }else{
                $this->error($result['message']);
            }
        }
    }

    public function getAliziPrice(){
        $data = array(
            'sn'=>$_POST['sn'],
            'quantity'=>(int)$_POST['quantity'],
            'item_params'=>trim($_POST['params']),
            'payment'=>(int)$_POST['payment'],
        );
        $data['sign'] = createSign($data,C('ALIZI_KEY'));
        $result = R('Api/getAliziPrice',array('data'=>$data));
        $this->ajaxReturn($result,'success',1);
    }

    public function query(){
        if(IS_POST){
            $kw = strFilter($_POST['kw']);
            $Model = M('Order');
            $OrderLog = M('OrderLog');
            $status = C('ORDER_STATUS');
            $where = "mobile='{$kw}' OR order_no='{$kw}' OR name='{$kw}'";
            $orders = $Model->where($where)->order('id desc')->select();
	
            $list = array();
            if($orders){
                foreach($orders as $li){
                    $item_extends = json_decode($li['item_extends'],true);
                    $itemExtends = '';
                    foreach($item_extends as $k=>$v){$itemExtends.=$k.lang('colon').(is_array($v)?implode(' ', $v):$v)."<br>";}
                    $list[] = array(
                        'title'=>$li['item_name'],
                        'order_no'=>$li['order_no'],
                        'order_status'=>(int)$li['status'],
                        'status'=>strip_tags($status[$li['status']]),
                        'payment'=>$li['payment'],
                        'quantity'=>$li['quantity'],
                        'price'=>$li['total_price'],
                        'name'=>$li['name'],
                        'params'=>$li['item_params'],
                        'itemExtends'=>$itemExtends,
                        'datetime'=>substr($li['datetime'],0,10),

                        'address'=>$li['region'].$li['address'],
                        'time'=>date('Y-m-d H:i:s',$li['add_time']),
                        'express'=>experss($li['delivery_name'],$li['delivery_no']),
                        'qq'=>$li['qq'],
                    );
                }
            }
            if($list){
                $this->ajaxReturn(array('title'=>'query','list'=>$list),'true',1);
            }else{
                $this->ajaxReturn(array('title'=>'query','list'=>null),lang('empty'),0);
            }
        }else{
            $this->display();
        }
    }
    public function apply(){
        if(IS_POST){
            $order_no = strFilter($_POST['order_no']);
            $mobile = strFilter($_POST['mobile']);
            $Model = M('Order');
            $where = array('order_no'=>$order_no,'mobile'=>$mobile);
            $order = $Model->where($where)->field('id,status')->find();

            if(empty($order)){
                $msg = lang('empty');
            }else{
                switch($order['status']){
                    case '1':
                        $msg = lang('applySuccess');
                        $data = array(
                            'order_id'=>$order['id'],
                            'status'=>8,
                            'remark'=>htmlspecialchars($_POST['refund_payment'].' , '.$_POST['refund_account']),
                        );
                        $data['sign'] = createSign($data,C('ALIZI_KEY'));
                        $rs = http($this->aliziHost."index.php?m=Api&a=aliziUpdateStatus", 'POST', array('data'=>$data));
                        break;
                    case '8':$msg = lang('applyIn');break;
                    default: $msg = lang('status_err');
                }
            }
            $this->ajaxReturn(1,$msg,1);
        }else{
            $this->display();
        }
    }

    public function pay(){
        $order_no = strFilter($_GET['order_no']);
        $order = M('Order')->where(array('order_no'=>$order_no))->find();
        if($order['status']!=0){
            $this->redirect('Order/result',array('order_no'=>$order['order_no']));
        }
        $payment = isset($_GET['payment'])?$_GET['payment']:$order['payment'];

		$redirectUrl = $order['url'];
		$options = json_decode($this->aliziConfig['order_options'],true);
		if(in_array($order['order_page'],array('single','detail'))){
			$template = M('ItemTemplate')->where(array('id'=>$order['item_id']))->field('redirect_uri,options')->find();
			if($template){
				$redirectUrl = $template['redirect_uri']=='1'?$order['referer']:$template['redirect_uri'];
				$options = json_decode($template['options'],true);
			}
		}
		$this->assign('redirectUrl',$redirectUrl);
				
        $this->assign('order',$order);
        switch ($payment) {
            case '2':
                $this->alipayInWx($order);
                $this->display('alipay');
                R('Api/payAlipay',array('data'=>$order));
                break;
            case '4':
                $this->alipayInWx($order);
                $this->display('result');
                D('Pay')->alipayDb($order,$this->aliziConfig);
                break;
            case '3':
                if(isWeixin()==true && in_array(2, json_decode($this->aliziConfig['wxpay_type'],true))){
                    $this->redirect('Order/payWxPayJsApi',array('order_id'=>$order['id']));exit;
                }elseif(isWeixin()==false && isMobile()==true){
					$this->redirect('Order/payWxPayWap',array('order_id'=>$order['id']));exit;
				}else{
                    $result = R('Api/payWxpay',array('data'=>$order));
                    if($result['return_code']=='FAIL'){
                        $this->error($result['return_msg']);
                    }else{
                        $this->assign('result',$result);
                        $this->display('payWxpay');
                    }
                }
                break;
            case '5'://二维码
                $qrcode = R('Api/payQrcode',array('data'=>$order));
                $this->assign('qrcode',$qrcode);

                
                $this->display('payQrcode');
                break;
            case '7':
                $this->yunpay($order);
                break;
            case '8':
                $this->display('alipay');
                $link = M('Item')->where(array('id'=>$order['item_id']))->getField('link_pay_url');
                header('location:'.$link);exit;
                break;
			case '9':
				Vendor('aiyangPay.aiyangPay');
				$aiyang = new aiyangPay($this->aliziConfig['ay_partner'],$this->aliziConfig['ay_key']);
				$data = array(
					'type'=>1007,
					'total_price'=>$order['total_price'],
					'out_trade_no'=>$order['order_no'].'-'.time(),
					'notify_url'=>$this->aliziHost.'Api/aiyangpay.php',
					'return_url'=>$this->aliziHost.'Api/aiyangpayCallbak.php',
					'attach'=>$order['order_no'],
				);
				$payURl = $aiyang->getPayUrl($data);
				header('location:'.$payURl);exit;
			break;
            default:$this->result($order);
        }
    }
    public function yunpay($order){

        $yun_config['partner'] = $this->aliziConfig['yunpay_pid'];//合作身份者id
        $yun_config['key'] = $this->aliziConfig['yunpay_key'];//安全检验码
        $seller_email = $this->aliziConfig['yunpay_email'];//云会员账户（邮箱）
        $GLOBALS['i2ekeys']=$yun_config['key'];
        Vendor('yunpay.lib.yun_md5#function');

        $out_trade_no = $order['order_no'];//商户网站订单系统中唯一订单号，必填
        $subject = $order['item_name'];//订单名称，必填
        $total_fee = $order['total_price'];//付款金额,必填 需为整数
        $body = $order['item_params'];//订单描述

        $nourl = $this->aliziHost.'Api/yunpay.php'; //服务器异步通知页面路径,需http://格式的完整路径,不能加参数
        $reurl = $this->aliziHost.'Api/yunpayCallbak.php';//页面跳转同步通知页面路径,需http://格式的完整路径，不能加?id=123这类自定义参数

        $orurl = '';
        //商品展示地址需http://格式的完整路径，不能加?id=123这类自定义参数，如原网站带有 参数请彩用伪静态或短网址解决
        $orimg = '';
        //商品形象图片地址 需http://格式的完整路径，必须为图片完整地址

        //构造要请求的参数数组，无需改动
        $parameter = array(
            "partner" => trim($yun_config['partner']),
            "seller_email"	=> $seller_email,
            "out_trade_no"	=> $out_trade_no,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "nourl"	=> $nourl,
            "reurl"	=> $reurl,
            "orurl"	=> $orurl,
            "orimg"	=> $orimg
        );
        //dump($parameter);exit;
        $html_text = i2e($parameter, "支付进行中...");
        echo $html_text;
    }
    public function payWxPayJsApi(){

        $order_id = intval($_GET['order_id']);
        $order = M('Order')->where(array('id'=>$order_id))->find();
        $redirectUrl = $this->aliziHost."index.php?m=Order&a=payWxPayJsApi&order_id={$order_id}";
        //$redirectUrl = $this->aliziHost."Api/wxPayJsApi.php?order_id={$order_id}";


        Vendor('wxPay.WxPay#JsApiPay');
        WxPayConfig::setConfig($this->aliziConfig);
        $JsApiPay = new JsApiPay();
        $openid = $JsApiPay->GetOpenid($redirectUrl);
        $total_price = $order['total_price']*100;//价格，单位为分

        $input = new WxPayUnifiedOrder();
        $input->SetOpenid($openid);
        $input->SetBody($order['item_name']);
        $input->SetOut_trade_no($order['order_no'].'-'.time());//$order['order_no']
        $input->SetTotal_fee($total_price);
        $input->SetProduct_id($order['item_id']);
        $input->SetAttach(L('aliziSystem'));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag('Alizi'.$order['order_no']);
        $input->SetNotify_url($this->aliziHost."Api/wxPay.php");
        $input->SetTrade_type("JSAPI");

        $param = WxPayApi::unifiedOrder($input);

        if(empty($param)){
            $this->error('error');exit;
        }
        if($param['result_code']=='FAIL'){
            $this->error($param['err_code_des']);exit;
        }
        $wxPayRequest = $param?$JsApiPay->GetJsApiParameters($param):array();
        $this->assign('wxPayRequest',$wxPayRequest);
        $this->assign('order',$order);
        $this->assign('config',$this->aliziConfig);
        $this->display('Order:payWxPayJsApi');

    }
	 public function payWxPayWap(){

        $order_id = intval($_GET['order_id']);
        $order = M('Order')->where(array('id'=>$order_id))->find();
        $redirectUrl = $this->aliziHost."Api/payWxPayH5.php?order_id={$order_id}";


        Vendor('wxPay.WxPay#JsApiPay');
        WxPayConfig::setConfig($this->aliziConfig);
        $total_price = $order['total_price']*100;//价格，单位为分

        $input = new WxPayUnifiedOrder();
        $input->SetBody($order['item_name']);
        $input->SetOut_trade_no($order['order_no'].'-'.time());//$order['order_no']
        $input->SetTotal_fee($total_price);
        $input->SetProduct_id($order['item_id']);
        $input->SetAttach(L('aliziSystem'));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag('Alizi'.$order['order_no']);
        $input->SetNotify_url($this->aliziHost."Api/wxPay.php");
        $input->SetTrade_type("MWEB");
        $input->SetSpbill_create_ip(get_client_ip());

        $param = WxPayApi::unifiedOrder($input);
		$mweb_url = $param['mweb_url'].'&redirect_url='.urlencode($this->aliziHost.'?m=Order&a=result&order_no=17091957052298');
		
		//print_r($mweb_url );exit;
		header("location:".$param['mweb_url']);
		

    }

    public function result($order=array()){
		
		$order_no = strFilter($_GET['order_no']);
        if(empty($order) && isset($_GET['order_no'])){
            $order = M('Order')->where(array('order_no'=>$order_no))->find();
        }

        //优惠券支付成功提示页面
        if(isset($_GET['order_no']) && strstr($order_no,'_')){
            $this->display('UserWap/paySuccess');exit;
        }

        $redirectUrl = $order['url'];
        $options = json_decode($this->aliziConfig['order_options'],true);

        if(in_array($order['order_page'],array('single','detail'))){
            $template = M('ItemTemplate')->where(array('id'=>$order['item_id']))->field('redirect_uri,options')->find();
            if($template){
                if($template['redirect_uri']=='1' && !empty($order['referer'])){
                    $redirectUrl = $order['referer'];
                }elseif($template['redirect_uri']!='1' && !empty($template['redirect_uri'])){
                    $redirectUrl = $template['redirect_uri'];
                }
                $options = json_decode($template['options'],true);
            }
        }

        foreach($options as $k=>$opt){ if(in_array($opt, array('salenum'))) unset($options[$k]); }
        $this->assign('options',$options);
        $this->assign('order',$order);
        $this->assign('redirectUrl',$redirectUrl);
        $this->display('result');
    }
    private function alipayInWx($data){
        if(isWeixin()==true){
            $this->assign('info',$data);
            $this->display('Order:payInWx');exit;
        }
    }
    //订单轮询
    public function orderQuery($order_no){
		$order_no = strFilter($order_no);
        if(strstr($order_no,'_')){
            $no = explode('_',$order_no);
            $status = M('User')->where(array('id'=>$no[0]))->getField('status');
            $this->ajaxReturn(null,null,(int)$status);
        }
        $status = M('Order')->where(array('order_no'=>$order_no))->getField('status');
        $this->ajaxReturn(null,null,(int)$status);
    }

    public function getComments(){
        if(IS_POST){
            $Model = M('Comments');
            $item_id = intval($_POST['item_id']);
            $currentPage = intval($_POST['currentPage']);
            $page = intval($_POST['page']);
            $order = isset($_POST['order'])?trim($_POST['order']):'id DESC';

            $where = array('item_id'=>$item_id,'status'=>1);
            $total = $Model->where($where)->count();
            $list = $Model->where($where)->limit($currentPage,$page)->order($order)->select();

            $count = count($list);
            $data = array(
                'list'=>$list,
                'currentPage'=>$currentPage+$count,
                'leftPage'=>$total-$currentPage-$count,
            );
            $this->ajaxReturn($data,1,1);
        }
    }
    public function comment(){
        if(IS_POST){
            $item_id = intval($_POST['item_id']);
            $name = strip_tags(trim($_POST['name']));
            $mobile = strip_tags(trim($_POST['mobile']));
            $content = strip_tags(trim($_POST['content']));
		
            if(empty($name) || mb_strlen($name,'utf-8')>5){  $this->ajaxReturn('name',lang('invalid_realname'),0);  }
            if(empty($mobile)){  $this->ajaxReturn('mobile',lang('invalid_mobile'),0);  }
            if(empty($content)){  $this->ajaxReturn('content',lang('content_notempty'),0); }
			
				
			$exist = M('Order')->where(array('item_id'=>$item_id,'mobile'=>$mobile))->field('id')->find();
			if(empty($exist)){
				$this->ajaxReturn('name',lang('commentErrorMessage'),0);
			}
			
            $str = http("http://ip.taobao.com/service/getIpInfo.php?ip=".get_client_ip());
            $json = json_decode($str,true);
            $address = $json['data']['region'];

            $data = array(
                'item_id'=>$item_id,
                'status'=>0,
                'mobile'=>$mobile,
                'region'=>$address,
                'name'=>$name,
                'content'=>$content,
                'add_time'=>date('Y-m-d'),
            );
            M('Comments')->add($data);
            $this->ajaxReturn(1,lang('submit_success'),1);
        }
    }
    public function getCode(){
        $item_id = intval($_POST['item_id']);
        $mobile = strFilter($_POST['mobile']);
        $verify = $_POST['verify'];
        $page = $_POST['page'];

        if(isMobileNum($mobile)==false){  $this->ajaxReturn(0,lang('pleaseInputMobile'),0);}
        if(in_array($page,array('single','detail'))){
            $options = M('ItemTemplate')->where(array('id'=>$item_id))->getField('options');
        }else{
            $options = $this->aliziConfig['order_options'];
        }
        $optionArr = json_decode($options,true);

        if(in_array('verify',$optionArr)){
            if(empty($verify))$this->ajaxReturn(0,lang('pleaseInputCode'),0);
            if(md5($verify)!=$_SESSION['verify']){ $this->ajaxReturn(0,lang('invalid_verify'),0);}
        }
        $code = randCode(4);

		$rs = parent::send_sms($mobile,sprintf(L('smsCodeContent'),$code));
        if(strtolower($rs['status'])=='1'){
            $data = array(
                'item_id'=>$item_id,
                'mobile'=>$mobile,
                'code'=>$code,
                'type'=>1,
                'status'=>0,
                'add_time'=>time(),
            );
            $flag = M('Code')->add($data);
            $this->ajaxReturn(1,lang('send_success'),1);
        }else{
            $this->ajaxReturn(0,lang('send_failure_colon').$rs['message'],0);
        }
    }
	 

    public function wx(){
		if($this->aliziConfig['weixin_status']){
			$url = trim($_GET['url']);
			Vendor('wxShare.jssdk');
			$jssdk = new JSSDK($this->aliziConfig['weixin_appid'], $this->aliziConfig['weixin_appsecret']);
			$signPackage = $jssdk->GetSignPackage($url);
			echo json_encode($signPackage);
		}
    }


}
